package org.hiberlyzer.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.hiberlyzer.Metadata;
import org.hiberlyzer.MetadataSource;
import org.hibernate.Session;
import org.hibernate.metadata.ClassMetadata;

public class MetadataSourceImpl implements MetadataSource
{
	private Map<String, ClassMetadata> allClassMetadataMap;
	private Session session;
	
	public MetadataSourceImpl(Session session)
	{
		this.session = session;
		this.allClassMetadataMap = session.getSessionFactory().getAllClassMetadata();
	}

	public Map<Class, Metadata> getAllClassMetadata()
	{
		Map<Class, Metadata> map = new HashMap<Class, Metadata>();
		Map<String, ClassMetadata> allClassMetadata = this.session.getSessionFactory().getAllClassMetadata();
		for(Entry<String, ClassMetadata> entry : allClassMetadata.entrySet())
		{
			Class mappedClass = entry.getValue().getMappedClass(session.getEntityMode());
			map.put(mappedClass, new MetadataImpl(entry.getValue(), session.getEntityMode()));
		}
		return map;
	}

	public Metadata getClassMetadata(Class c)
	{
		ClassMetadata hibernateClassMetadata = session.getSessionFactory().getClassMetadata(c);
		return new MetadataImpl(hibernateClassMetadata, session.getEntityMode());
	}

	public Metadata getObjectMetadata(Object o)
	{
		String entityName = session.getEntityName(o);
		ClassMetadata hibernateClassMetadata = session.getSessionFactory().getClassMetadata(entityName);
		return new MetadataImpl(hibernateClassMetadata, session.getEntityMode());
	}

}
